package com.sunyard.utils;

import cn.hutool.http.HttpRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;

/**
 * @Auther: yanj.yang
 * @Date: Create in 2020/7/8 9:32
 * @Description
 */
public class IpUtils {
    private static final String UNKNOWN = "unknown";

    /**
     * 获取IP地址
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
    }

    /**
     * 获取请求终端的IP
     *
     * @return
     */
    public static String getRemoteIp() {
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();
        return getIpAddr(request);
    }

    /**
     * 获取本机内网IP
     */
    public static String getLocalIp() {

        return ExtendsSimpleUtil.getServerIp02();

//        try {
//            InetAddress address=InetAddress.getLocalHost();
//            String localIp=address.getHostAddress();
//            return localIp;
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//        return null;

    }
}
